package com.ys.controller.api.base;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.business.TbRepeatWord;
import com.ys.service.business.TbRepeatWordService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.excel.ReadExcel;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

import lombok.AllArgsConstructor;
import lombok.Data;

@Controller
@RequestMapping("/api/inter/tbRepeatWord")
public class ApiInterTbRepeatWordController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<TbRepeatWord> commonApiService;
	@Autowired
	private TbRepeatWordService tbRepeatWordService;

	@RequiresPermissions("tbRepeatWord:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TbRepeatWord cond
			){
		
		return commonApiService.searchLay(cond);
	}
	
	/**
	 * 新增
	 */
	@RequiresPermissions("tbRepeatWord:add")
	@PostMapping("/add")
    @ResponseBody
	public R add(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			return tbRepeatWordService.add(params);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/**
	 * 编辑
	 */
	@RequiresPermissions("tbRepeatWord:edit")
	@PostMapping("/edit")
    @ResponseBody
	public R edit(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			return tbRepeatWordService.edit(params);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/*
	 * 彻底删除
	 */
	@PostMapping("/deleteTrue")
	@ResponseBody
	public R deleteTrue(HttpServletRequest request, HttpServletResponse response,
			String guid) {
		return tbRepeatWordService.deleteTrue(guid);
	}

    @PostMapping("/uploadAndReadExcelBatchImport")
    @ResponseBody
	public R uploadAndReadExcelBatchImport(@RequestParam("file") MultipartFile uploadfile) throws Exception {
    	

		try {
			InputStream fileInputStream = uploadfile.getInputStream();
			
			// 文件初始名
			String sourceFilename = uploadfile.getOriginalFilename();
	    	if (!sourceFilename.endsWith(".xlsx")) {
				return R.error("请按照模板xlsx进行导入");
			}
			List<List<String>> data = ReadExcel.getRowsByInputStream(fileInputStream, 0);
			
			List<TableDto.RowDto> rows = new ArrayList<TableDto.RowDto>();
			if (rows != null && rows.size() > 300) {
				return R.error("导入数量不能超过300条");
			}
			for (int i = 1, index = 1; data != null && i < data.size(); i++) {
				List<String> row = data.get(i);

				
				String country = row.get(0);
				
				String name = row.get(1);
				TableDto.RowDto rowDto = new TableDto.RowDto(index, country, name);
				rows.add(rowDto);
				index++;
			}
			TableDto dto = new TableDto(rows);
			return R.ok(dto);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("数据有误，请联系客服");
		}
	}
	@Data
	@AllArgsConstructor
	public static class TableDto{
		private List<RowDto> rows; // 数组
		
		@Data
		@AllArgsConstructor
		public static class RowDto {
			private int index; // 序号
			private String country; // 国家
			private String name; // 单词
		}
	}
    
    /**
     * 批量新增商品库——数据提交
     */
	@RequiresPermissions("tbRepeatWord:batchImport")
    @PostMapping("/batchImport")
    @ResponseBody
    public R batchImport(String detailArr){
    	
    	if (detailArr == null || detailArr.length() == 0) {
			return R.error("导入出错，请联系技术");
		}
    	JSONArray detailJA = JSON.parseArray(detailArr);
    	for (int i = 0; i < detailJA.size(); i++) {
    		
			JSONObject detailJO = detailJA.getJSONObject(i);

    		Map<String, Object> params = new HashMap<String, Object>();
    		for(Map.Entry<String, Object> e : detailJO.entrySet()) {
    			params.put(e.getKey(), e.getValue());
    		}
	        try {
	        	tbRepeatWordService.add(params);
	        
	        }catch (Exception e) {
	        	e.printStackTrace();
	            return R.error();
	        }
		}
        return R.ok("操作成功");
    }
}
